<template>
  <div class="dashboard-container">
    <!-- 简化的头部 -->
    <header class="dashboard-header">
      <div class="header-content">
        <div class="logo-section">
          <div class="logo-icon">⭐</div>
          <span class="logo-text">Sparkie Interview</span>
        </div>
        
        <div class="user-section">
          <el-dropdown>
            <span class="user-avatar">
              <el-avatar :size="40">{{ user?.name?.charAt(0) || 'C' }}</el-avatar>
              <span class="user-name">{{ user?.name || '候选人' }}</span>
              <el-icon class="dropdown-icon"><ArrowDown /></el-icon>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item>个人设置</el-dropdown-item>
                <el-dropdown-item divided @click="handleLogout">退出登录</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>
    </header>
    
    <!-- 主要内容区域 -->
    <main class="dashboard-main">
      <div class="dashboard-content">
        <!-- 欢迎区域 -->
        <div class="welcome-section">
          <div class="welcome-content">
            <h1 class="welcome-title">{{ getGreeting() }}，{{ user?.name || '候选人' }}！</h1>
            <p class="welcome-subtitle">准备开始您的面试之旅</p>
          </div>
          <div class="welcome-illustration">
            <div class="illustration-circle"></div>
          </div>
        </div>
        
        <!-- 已投递简历的面试列表 -->
        <div class="submitted-interviews">
          <div class="section-header">
            <h2>我的面试安排</h2>
            <el-button type="primary" link @click="viewAllInterviews">查看全部</el-button>
          </div>
          
          <div v-if="loading" class="loading-container">
            <el-skeleton :rows="3" animated v-for="n in 3" :key="n" />
          </div>
          
          <div v-else class="interview-list">
            <div 
              v-for="interview in submittedInterviews" 
              :key="interview.id"
              class="interview-item"
              :class="interview.status"
            >
              <div class="interview-info">
                <div class="company-logo">
                  <div class="logo-placeholder">{{ interview.company.charAt(0) }}</div>
                </div>
                <div class="interview-details">
                  <h3>{{ interview.position }}</h3>
                  <p class="company-name">{{ interview.company }}</p>
                  <div class="interview-meta">
                    <span class="meta-item">
                      <el-icon><Location /></el-icon>
                      {{ interview.location }}
                    </span>
                    <span class="meta-item">
                      <el-icon><Calendar /></el-icon>
                      {{ formatDate(interview.submittedTime) }}
                    </span>
                    <span v-if="interview.matchScore" class="meta-item">
                      <el-icon><Document /></el-icon>
                      匹配度: {{ interview.matchScore.toFixed(1) }}%
                    </span>
                  </div>
                </div>
              </div>
              
              <div class="interview-status">
                <el-tag 
                  :type="getStatusType(interview.status)"
                  class="status-tag"
                >
                  {{ getStatusText(interview.status) }}
                </el-tag>
                
                <div class="interview-actions">
                  <el-button 
                    v-if="interview.status === 'screened_pass'"
                    type="primary"
                    size="small"
                    @click="startInterview(interview)"
                  >
                    开始面试
                  </el-button>
                  <el-button 
                    v-else-if="interview.status === 'passed'"
                    type="success"
                    size="small"
                    @click="viewResult(interview)"
                  >
                    查看结果
                  </el-button>
                  <el-button 
                    v-else-if="interview.status === 'rejected' || interview.status === 'screened_fail'"
                    type="info"
                    size="small"
                    @click="viewFeedback(interview)"
                  >
                    查看反馈
                  </el-button>
                  <el-button 
                    v-else
                    type="info"
                    size="small"
                    disabled
                  >
                    等待审核
                  </el-button>
                </div>
                
                <div v-if="interview.status === 'screened_pass'" class="interview-time">
                  <span>可以开始面试</span>
                </div>
              </div>
            </div>
            
            <div v-if="submittedInterviews.length === 0" class="empty-state">
              <el-empty description="暂无面试安排">
                <el-button type="primary" @click="viewJobs">去投递简历</el-button>
              </el-empty>
            </div>
          </div>
        </div>
        
        <!-- 主要操作区域 -->
        <div class="action-section">
          <!-- 正式面试入口 -->
          <div class="action-card primary" @click="startInterview">
            <div class="card-header">
              <div class="card-icon primary">
                <el-icon><VideoPlay /></el-icon>
              </div>
              <div class="card-badge primary">正式面试</div>
            </div>
            <div class="card-content">
              <h3 class="card-title">正式面试入口</h3>
              <p class="card-description">开始您的正式AI面试，展示您的实力</p>
              <div class="card-features">
                <span class="feature-item">🎯 智能评估</span>
                <span class="feature-item">📹 视频记录</span>
                <span class="feature-item">🏆 实时反馈</span>
              </div>
            </div>
          </div>
          
          <!-- 模拟练习入口 -->
          <div class="action-card secondary" @click="startPractice">
            <div class="card-header">
              <div class="card-icon secondary">
                <el-icon><Edit /></el-icon>
              </div>
              <div class="card-badge secondary">模拟练习</div>
            </div>
            <div class="card-content">
              <h3 class="card-title">模拟练习入口</h3>
              <p class="card-description">通过模拟练习提升您的面试技能</p>
              <div class="card-features">
                <span class="feature-item">🎯 阶段选择</span>
                <span class="feature-item">📊 即时评估</span>
                <span class="feature-item">🔄 换题练习</span>
              </div>
            </div>
          </div>
          
          <!-- 查看过往练习记录 -->
          <div class="action-card tertiary" @click="viewHistory">
            <div class="card-header">
              <div class="card-icon tertiary">
                <el-icon><Document /></el-icon>
              </div>
              <div class="card-badge tertiary">练习记录</div>
            </div>
            <div class="card-content">
              <h3 class="card-title">查看过往练习记录</h3>
              <p class="card-description">回顾您的练习历史和成长轨迹</p>
              <div class="card-stats">
                <div class="stat-item">
                  <span class="stat-number">{{ historyStats.totalSessions }}</span>
                  <span class="stat-label">总练习次数</span>
                </div>
                <div class="stat-item">
                  <span class="stat-number">{{ historyStats.averageScore }}</span>
                  <span class="stat-label">平均分数</span>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 查看招聘岗位 -->
          <div class="action-card quaternary" @click="viewJobs">
            <div class="card-header">
              <div class="card-icon quaternary">
                <el-icon><Search /></el-icon>
              </div>
              <div class="card-badge quaternary">招聘岗位</div>
            </div>
            <div class="card-content">
              <h3 class="card-title">查看招聘岗位</h3>
              <p class="card-description">浏览并申请心仪的工作机会</p>
              <div class="card-features">
                <span class="feature-item">🔍 智能搜索</span>
                <span class="feature-item">📋 简历投递</span>
                <span class="feature-item">🎯 匹配度分析</span>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 成绩趋势 -->
        <div class="trend-section">
          <div class="trend-header">
            <h3 class="trend-title">练习成绩趋势</h3>
            <el-button type="primary" link @click="viewDetailedStats">查看详细统计</el-button>
          </div>
          
          <div class="trend-chart">
            <div class="chart-placeholder">
              <div class="trend-line">
                <div 
                  v-for="(score, index) in trendData" 
                  :key="index"
                  class="trend-point"
                  :style="{ left: `${(index / (trendData.length - 1)) * 100}%`, bottom: `${score}%` }"
                  :title="`第${index + 1}次练习: ${score}分`"
                ></div>
              </div>
            </div>
            <div class="chart-labels">
              <span class="label-start">最早</span>
              <span class="label-end">最新</span>
            </div>
          </div>
          
          <div class="trend-insights">
            <div class="insight-item">
              <span class="insight-icon">📈</span>
              <span class="insight-text">您的表现正在稳步提升</span>
            </div>
            <div class="insight-item">
              <span class="insight-icon">🎯</span>
              <span class="insight-text">建议多练习技术类题目</span>
            </div>
          </div>
        </div>
      </div>
    </main>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { ElMessage } from 'element-plus'
import { candidateApi } from '@/services/api'
import { 
  ArrowDown,
  VideoPlay,
  Edit,
  Document,
  Clock,
  Calendar,
  Search,
  Location
} from '@element-plus/icons-vue'

export default {
  name: 'CandidateDashboard',
  components: {
    ArrowDown,
    VideoPlay,
    Edit,
    Document,
    Clock,
    Calendar,
    Search,
    Location
  },
  setup() {
    const router = useRouter()
    const authStore = useAuthStore()
    
    // 响应式数据
    const submittedInterviews = ref([])
    const loading = ref(false)
    
    const historyStats = ref({
      totalSessions: 12,
      averageScore: 85
    })
    
    const trendData = ref([65, 72, 78, 81, 85, 88, 92])
    
    // 计算属性
    const user = computed(() => authStore.user)
    
    // 方法
    const getGreeting = () => {
      const hour = new Date().getHours()
      if (hour < 12) return '早上好'
      if (hour < 18) return '下午好'
      return '晚上好'
    }
    
    const startInterview = (interview) => {
      if (interview) {
        // 传递面试信息到面试页面，使用applicationId参数
        router.push({
          path: '/candidate/interview-session',
          query: { applicationId: interview.id }
        })
      } else {
        // 从正式面试入口进入
        router.push('/candidate/interview-session')
      }
    }
    
    const startPractice = () => {
      router.push('/candidate/practice')
    }
    
    const viewHistory = () => {
      router.push('/candidate/practice-history') // 跳转到练习历史页面
    }
    
    const viewJobs = () => {
      router.push('/candidate/search-interviews')
    }
    
    const viewAllInterviews = () => {
      router.push('/candidate/my-interviews')
    }
    
    const viewResult = (interview) => {
      router.push({
        path: '/candidate/interview-result',
        query: { 
          id: interview.id,
          status: interview.status === 'passed' ? 'passed' : 'failed'
        }
      })
    }
    
    const viewFeedback = (interview) => {
      router.push({
        path: '/candidate/interview-feedback', 
        query: { id: interview.id }
      })
    }
    
    const getStatusType = (status) => {
      const statusMap = {
        'scheduled': 'success',
        'passed': 'success',
        'rejected': 'danger',
        'pending': 'warning'
      }
      return statusMap[status] || 'info'
    }
    
    const getStatusText = (status) => {
      const statusMap = {
        'screened_pass': '简历筛选通过',
        'screened_fail': '简历筛选未通过',
        'interview_scheduled': '已安排面试',
        'interview_completed': '面试完成',
        'passed': '面试通过',
        'rejected': '未通过',
        'pending': '审核中'
      }
      return statusMap[status] || '未知状态'
    }
    
    const viewDetailedStats = () => {
      router.push('/candidate/statistics')
    }
    
    const handleLogout = async () => {
      await authStore.logout()
      router.push('/login')
    }
    
    const formatDate = (dateString) => {
      return new Date(dateString).toLocaleDateString('zh-CN', {
        month: 'long',
        day: 'numeric'
      })
    }
    
    const formatDateTime = (dateString) => {
      return new Date(dateString).toLocaleDateString('zh-CN', {
        month: 'long',
        day: 'numeric',
        hour: '2-digit',
        minute: '2-digit'
      })
    }
    
    // 获取我的申请列表
    const fetchMyApplications = async () => {
      loading.value = true
      try {
        const response = await candidateApi.getMyApplications()
        submittedInterviews.value = response.results.map(app => ({
          id: app.id,
          company: app.company || '未知公司',
          position: app.job_title,
          location: '远程', // 后端没有提供location字段，使用默认值
          status: app.status,
          submittedTime: app.applied_at,
          scheduledTime: null, // 后端没有提供scheduled_time字段
          matchScore: app.match_score,
          requiredMatchScore: app.required_match_score
        }))
      } catch (error) {
        console.error('获取申请列表失败:', error)
        ElMessage.error('获取申请列表失败')
      } finally {
        loading.value = false
      }
    }

    // 生命周期
    onMounted(() => {
      console.log('候选人仪表盘加载完成')
      fetchMyApplications()
    })
    
    return {
      user,
      submittedInterviews,
      loading,
      historyStats,
      trendData,
      getGreeting,
      startInterview,
      startPractice,
      viewHistory,
      viewJobs,
      viewAllInterviews,
      viewResult,
      viewFeedback,
      viewDetailedStats,
      handleLogout,
      formatDate,
      formatDateTime,
      getStatusType,
      getStatusText
    }
  }
}
</script>

<style scoped>
.dashboard-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
}

.dashboard-header {
  background: white;
  border-bottom: 1px solid var(--border-color);
  box-shadow: var(--shadow-sm);
}

.header-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 24px;
  height: 64px;
  max-width: 1200px;
  margin: 0 auto;
}

.logo-section {
  display: flex;
  align-items: center;
  gap: 12px;
}

.logo-icon {
  font-size: 24px;
  color: var(--primary-color);
}

.logo-text {
  font-size: 18px;
  font-weight: 600;
  color: var(--text-primary);
}

.user-section {
  display: flex;
  align-items: center;
}

.user-avatar {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
}

.user-name {
  font-size: 14px;
  font-weight: 500;
  color: var(--text-primary);
}

.dropdown-icon {
  font-size: 12px;
  color: var(--text-secondary);
}

.dashboard-main {
  padding: 24px;
}

.dashboard-content {
  max-width: 1200px;
  margin: 0 auto;
}

.welcome-section {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: white;
  padding: 40px;
  border-radius: 16px;
  margin-bottom: 32px;
  box-shadow: var(--shadow-sm);
}

.welcome-content {
  flex: 1;
}

.welcome-title {
  font-size: 2.5rem;
  font-weight: 700;
  color: var(--text-primary);
  margin-bottom: 12px;
}

.welcome-subtitle {
  font-size: 1.2rem;
  color: var(--text-secondary);
}

.welcome-illustration {
  position: relative;
  width: 120px;
  height: 120px;
}

.illustration-circle {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
  opacity: 0.8;
}

.submitted-interviews {
  background: white;
  padding: 32px;
  border-radius: 16px;
  margin-bottom: 32px;
  box-shadow: var(--shadow-sm);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.section-header h2 {
  color: var(--text-primary);
  font-size: 1.3rem;
  font-weight: 600;
  margin: 0;
}

.loading-container {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.interview-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.interview-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px;
  border: 1px solid var(--border-color);
  border-radius: 8px;
  background: #f8f9fa;
  transition: all 0.3s ease;
}

.interview-item:hover {
  background: #f0f2f5;
  border-color: var(--primary-color);
}

.interview-item.scheduled {
  border-left: 4px solid #67c23a;
}

.interview-item.passed {
  border-left: 4px solid #67c23a;
}

.interview-item.rejected {
  border-left: 4px solid #f56c6c;
}

.interview-item.pending {
  border-left: 4px solid #e6a23c;
}

.interview-info {
  display: flex;
  align-items: center;
  gap: 16px;
  flex: 1;
}

.company-logo {
  width: 48px;
  height: 48px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: var(--primary-color);
  color: white;
  font-weight: 600;
  font-size: 20px;
}

.logo-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: var(--primary-color);
  color: white;
  font-weight: 600;
  font-size: 20px;
  border-radius: 8px;
}

.interview-details h3 {
  color: var(--text-primary);
  font-size: 16px;
  font-weight: 600;
  margin: 0 0 4px 0;
}

.company-name {
  color: var(--text-secondary);
  font-size: 14px;
  margin: 0 0 8px 0;
}

.interview-meta {
  display: flex;
  gap: 16px;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 4px;
  color: var(--text-secondary);
  font-size: 12px;
}

.interview-status {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 8px;
}

.status-tag {
  margin-bottom: 8px;
}

.interview-actions {
  display: flex;
  gap: 8px;
}

.interview-time {
  font-size: 12px;
  color: var(--text-secondary);
  text-align: right;
}

.empty-state {
  text-align: center;
  padding: 40px 20px;
}

.interview-title {
  font-size: 1.5rem;
  font-weight: 600;
  color: var(--text-primary);
}

.interview-progress {
  margin-bottom: 24px;
}

.progress-info {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}

.progress-text {
  color: var(--text-secondary);
  font-size: 14px;
}

.progress-value {
  color: var(--text-primary);
  font-weight: 600;
}

.progress-bar {
  width: 100%;
}

.interview-actions {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.continue-button {
  height: 48px;
  padding: 0 32px;
  font-size: 16px;
  font-weight: 600;
}

.interview-meta {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 8px;
  color: var(--text-secondary);
  font-size: 14px;
}

.action-section {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 24px;
  margin-bottom: 32px;
}

.action-card {
  background: white;
  border-radius: 16px;
  overflow: hidden;
  box-shadow: var(--shadow-sm);
  border: 1px solid var(--border-color);
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
}

.action-card:hover {
  transform: translateY(-4px);
  box-shadow: var(--shadow-lg);
}

.action-card.primary {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.action-card.secondary {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
  color: white;
}

.action-card.tertiary {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  color: white;
}

.action-card.quaternary {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
  color: white;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 24px 24px 0;
}

.card-icon {
  width: 48px;
  height: 48px;
  border-radius: 12px;
  background: rgba(255, 255, 255, 0.1);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
}

.card-icon.large {
  width: 64px;
  height: 64px;
  font-size: 32px;
}

.action-card:not(.large) .card-icon {
  background: rgba(103, 83, 192, 0.1);
  color: var(--primary-color);
}

.card-badge {
  background: rgba(255, 255, 255, 0.2);
  color: white;
  padding: 4px 12px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
  border: 1px solid rgba(255, 255, 255, 0.3);
}

.action-card:not(.primary):not(.secondary):not(.tertiary):not(.quaternary) .card-badge {
  background: rgba(103, 83, 192, 0.1);
  color: var(--primary-color);
  border: 1px solid rgba(103, 83, 192, 0.2);
}

.card-content {
  padding: 24px;
}

.card-title {
  font-size: 1.3rem;
  font-weight: 600;
  margin-bottom: 8px;
  color: inherit;
}

.card-description {
  color: inherit;
  opacity: 0.9;
  margin-bottom: 16px;
}

.card-features {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.feature-item {
  font-size: 14px;
  color: var(--text-secondary);
}

.action-card.primary .feature-item,
.action-card.secondary .feature-item,
.action-card.tertiary .feature-item,
.action-card.quaternary .feature-item {
  color: rgba(255, 255, 255, 0.85);
}

.action-card.primary .card-title,
.action-card.secondary .card-title,
.action-card.tertiary .card-title,
.action-card.quaternary .card-title {
  color: white;
}

.action-card.primary .card-description,
.action-card.secondary .card-description,
.action-card.tertiary .card-description,
.action-card.quaternary .card-description {
  color: rgba(255, 255, 255, 0.9);
}

.action-card.primary .stat-number,
.action-card.secondary .stat-number,
.action-card.tertiary .stat-number,
.action-card.quaternary .stat-number {
  color: white;
}

.action-card.primary .stat-label,
.action-card.secondary .stat-label,
.action-card.tertiary .stat-label,
.action-card.quaternary .stat-label {
  color: rgba(255, 255, 255, 0.85);
}

.card-footer {
  padding: 0 24px 24px;
}

.practice-button {
  width: 100%;
  height: 40px;
}

.card-stats {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
  padding: 16px 24px 24px;
  border-top: 1px solid var(--border-color);
}

.stat-item {
  text-align: center;
}

.stat-number {
  display: block;
  font-size: 1.5rem;
  font-weight: 600;
  color: var(--text-primary);
  margin-bottom: 4px;
}

.stat-label {
  font-size: 12px;
  color: var(--text-secondary);
}

.trend-section {
  background: white;
  padding: 32px;
  border-radius: 16px;
  box-shadow: var(--shadow-sm);
}

.trend-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.trend-title {
  font-size: 1.3rem;
  font-weight: 600;
  color: var(--text-primary);
}

.trend-chart {
  margin-bottom: 24px;
}

.chart-placeholder {
  height: 120px;
  border: 2px dashed var(--border-color);
  border-radius: 8px;
  position: relative;
  background: var(--bg-light);
}

.trend-line {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

.trend-point {
  position: absolute;
  width: 8px;
  height: 8px;
  background: var(--primary-color);
  border-radius: 50%;
  transform: translate(-50%, 50%);
  cursor: pointer;
}

.chart-labels {
  display: flex;
  justify-content: space-between;
  margin-top: 8px;
  font-size: 12px;
  color: var(--text-secondary);
}

.trend-insights {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.insight-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 16px;
  background: var(--bg-light);
  border-radius: 8px;
}

.insight-icon {
  font-size: 20px;
}

.insight-text {
  color: var(--text-secondary);
  font-size: 14px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .dashboard-main {
    padding: 16px;
  }
  
  .welcome-section {
    flex-direction: column;
    text-align: center;
    padding: 24px;
  }
  
  .welcome-title {
    font-size: 2rem;
  }
  
  .action-section {
    grid-template-columns: 1fr;
  }
  
  .interview-actions {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .interview-meta {
    align-items: center;
  }
}
</style> 